/**   
 *    
 * 项目名称：SmartKungFuService   
 * 类名称：MstOrderServiceImpl   
 * 类描述：   订单实现类层
 * 创建人：zhangl  
 * 创建时间：2016年9月27日 下午7:40:36   
 * 修改人：zhangl   
 * 修改时间：2016年9月27日 下午7:40:36   
 * 修改备注：   
 * @version    
 *    
 */
package com.lst.service.impl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.github.miemiedev.mybatis.paginator.domain.PageBounds;
import com.lst.common.CommCode;
import com.lst.dao.ClientAccomplishMapper;
import com.lst.dao.ClientGrowthMapper;
import com.lst.dao.GymnasiumDetailMapper;
import com.lst.dao.MstCodeMapper;
import com.lst.dao.MstGradeMapper;
import com.lst.dao.MstGymnasiumMapper;
import com.lst.dao.MstOrderMapper;
import com.lst.dao.OrderDetailMapper;
import com.lst.dao.ProjectInfoMapper;
import com.lst.model.ClientAccomplish;
import com.lst.model.ClientGrowth;
import com.lst.model.GymnasiumDetail;
import com.lst.model.MstCode;
import com.lst.model.MstGrade;
import com.lst.model.MstGymnasium;
import com.lst.model.MstOrder;
import com.lst.model.OrderDetail;
import com.lst.model.ProjectInfo;
import com.lst.model.vo.MstOrderVo;
import com.lst.service.MstOrderService;
import com.lst.utils.CommFunUtils;
import com.lst.utils.DateUtil;

/**
 * @ClassName: MstOrderServiceImpl
 * @Description: 订单实现类层
 * @author zhangl
 * @date 2016年9月27日 下午7:40:36
 * 
 */
@Service("mstOrderService")
public class MstOrderServiceImpl implements MstOrderService {

	private Logger logger = Logger.getLogger("log");

	@Autowired
	private GymnasiumDetailMapper gymnasiumDetailMapper;

	@Autowired
	private MstGymnasiumMapper mstGymnasiumMapper;

	@Autowired
	private ProjectInfoMapper projectInfoMapper;

	@Autowired
	private MstOrderMapper dao;

	@Autowired
	private OrderDetailMapper odDao;

	@Autowired
	private ClientGrowthMapper cgDao;

	@Autowired
	private MstCodeMapper mstCodeDao;

	@Autowired
	private MstGradeMapper mstGradeDao;

	@Autowired
	private ClientAccomplishMapper clientAccomplishDao;

	public int deleteByPrimaryKey(Integer id) {
		return dao.deleteByPrimaryKey(id);
	}

	public int insert(MstOrder record) {
		return dao.insert(record);
	}

	public int insertSelective(MstOrder record) {
		return dao.insertSelective(record);
	}

	public MstOrder selectByPrimaryKey(Integer id) {
		return dao.selectByPrimaryKey(id);
	}

	public int updateByPrimaryKeySelective(MstOrder record) {
		return dao.updateByPrimaryKeySelective(record);
	}

	public int updateByPrimaryKey(MstOrder record) {
		return dao.updateByPrimaryKey(record);
	}

	/**
	 * 
	 * @Title: updateOrderAndOthers
	 * @Description:更新订单和其他业务逻辑
	 * @param @param mstOrder
	 * @param @return 设定文件
	 * @return ClientGrowth 返回类型
	 */
	@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
	public void updateOrderAndOthers(MstOrder mstOrder,OrderDetail orderDetail) {
		Date startDate = new Date();
		logger.info("updateOrderAndOthers begin：" + startDate);

		dao.updateByPrimaryKeySelective(mstOrder);
		odDao.updateByPrimaryKeySelective(orderDetail);

		MstOrder tempOrder = dao.selectByPrimaryKey(mstOrder.getId());
		OrderDetail tempod = odDao.selectByPrimaryKey(orderDetail.getId());

	//	ClientGrowth cg = null;		

		if (CommCode.SYSTEM_ORDER_STATUS_WAIT.equals(tempod.getOrderstatus())) {
		
			// 用户成就
	//		cg = new ClientGrowth();

	//		cg.setClientid(tempOrder.getClientid());
	//		cg.setGrowthid(tempOrder.getId());

//			if (tempOrder.getActtype() == 11) {// 购买活动
//				cg.setGrowthtype(CommCode.SYSTEM_GROWTH_RANGE_BUY_ACTY);
//			} else if (tempOrder.getActtype() == 298) {// 购买课程
//				cg.setGrowthtype(CommCode.SYSTEM_GROWTH_RANGE_BUY_COURSE);
//			}

//			MstCode code = mstCodeDao.selectByPrimaryKey(cg.getGrowthtype());
//			cg.setGrowthvalue(Integer.parseInt(code.getCode()));
//			cg.setEnabled(true);
//			cg.setIsdeleted(false);
//
//			cg.setCreatedate(startDate);
//			cg.setCreateuser(tempOrder.getClientid());
//
//			cgDao.insert(cg);

			// 查询用户成就表里
	//		List<ClientAccomplish> calist = clientAccomplishDao.queryByUser(tempOrder.getClientid());

//			if (calist != null && !calist.isEmpty()) {
//				// 当前达到的功力等级
//				ClientAccomplish ca = calist.get(0);
//				BigDecimal newGrowth = ca.getGrowthvalue().add(
//						new BigDecimal(code.getCode()));
//				// 查询功力值等级
//				Map<String, Object> graMap = new HashMap<String, Object>();
//
//				graMap.put("enabled", true);
//				graMap.put("isDeleted", false);
//				graMap.put("orderByClause", "mg.gravalue asc");
//
//				List<MstGrade> mglist = mstGradeDao.queryByList(graMap,
//						new PageBounds());
//
//				for (int i = 0; i < mglist.size(); i++) {
//					MstGrade mstGrade = mglist.get(i);
//					MstGrade nextGrade = null;
//					if (i == mglist.size() - 1) {
//						nextGrade = mstGrade;
//					} else {
//						nextGrade = mglist.get(i + 1);
//					}
//					// 如果等于当前等级
//					if (mstGrade.getGravalue() == ca.getGrade()) {
//
//						dealClientAccomplish(newGrowth, mglist, i, ca,
//								tempOrder.getClientid());
//					}
//				}
//			} else {
//				// 插入新的成就数据时
//				ClientAccomplish c = new ClientAccomplish();
//				c.setClientid(tempOrder.getClientid());
//				c.setGrade(1);
//				c.setGrowthvalue(new BigDecimal(code.getCode()));
//				c.setEnabled(true);
//				c.setIsdeleted(false);
//				c.setCreatedate(new Date());
//
//				clientAccomplishDao.insert(c);
//			}

			try {
				String title = "-";
				String address = "-";
				if (CommCode.SYSTEM_CARESEL_RANGE_PRO.equals(tempOrder.getActtype())) {// 活动
					ProjectInfo projectInfo = projectInfoMapper
							.selectByPrimaryKey(tempOrder.getActid());
					title = projectInfo.getTitle();
					address = projectInfo.getAddress();
				} else {
					GymnasiumDetail gd = gymnasiumDetailMapper
							.selectByPrimaryKey(tempOrder.getActid());
					MstGymnasium mstGymnasium = mstGymnasiumMapper
							.selectByPrimaryKey(gd.getGymid());
					title = gd.getCoursename();
					address = mstGymnasium.getAddress();

				}
				try {
					// 短息发送
					String[] scheIds = tempOrder.getScheid().split(" ");

					Date tempDate = DateUtil.parse(scheIds[0],
							DateUtil.ALL_DATE_HORIZONTAL);
					String scheId = DateUtil.date2Str(tempDate,
							DateUtil.ALL_DATETIME_SEPARATOR_CHINA);

					if (scheIds.length >= 2) {
						scheId += scheIds[1];
					}
					List<NameValuePair> formparams = new ArrayList<NameValuePair>();

					String content = String.format("%s|%s|%s", title, scheId,
							address);

					formparams.add(new BasicNameValuePair("userid", tempOrder
							.getClientid().toString()));
					formparams.add(new BasicNameValuePair("receivetype",
							(CommCode.SYSCODE_MSG_RECEIVE_TYPE_CLIENT)
							.toString()));
					formparams.add(new BasicNameValuePair("mobileno", tempOrder
							.getPhoneno()));
					formparams.add(new BasicNameValuePair("mirror", "payment"));
					formparams.add(new BasicNameValuePair("values", content));

					String result = CommFunUtils.sendSMS(formparams,CommCode.SMS_URL);

					logger.info("decPara result: " + result);
					
					//发送邮件
					List<NameValuePair> mailParas = new ArrayList<NameValuePair>();

					mailParas.add(new BasicNameValuePair("userid", "-1"));
					mailParas.add(new BasicNameValuePair("receivetype",(CommCode.SYSCODE_MSG_TYPE_RECEIVE_USER).toString()));
					mailParas.add(new BasicNameValuePair("mail", CommCode.TARGET_MAILNO));
					mailParas.add(new BasicNameValuePair("orderno", tempOrder.getOrderno()));
					
					String mailResult = CommFunUtils.sendSMS(mailParas,CommCode.MAIL_URL);
					logger.info("decPara mailResult: " + mailResult);
				} catch (Exception e) {
					logger.error("sendSMS error: ", e);
				}
			} catch (Exception e) {
				logger.error("doPost error:", e);
			}

		}

		logger.info("updateOrderAndOthers end: "
				+ DateUtil.calLastedTime(startDate));

	//	return cg;
	}

	public void dealClientAccomplish(BigDecimal newGrowth,
			List<MstGrade> mglist, int i, ClientAccomplish ca, int clientid) {
		if (i == mglist.size() - 1) {
			return;
		}
		MstGrade nextGrade = mglist.get(i + 1);
		// 如果等于当前等级

		// 如果增加后的功力值大于下一等级,增加数据
		if (newGrowth.compareTo(new BigDecimal(nextGrade.getGrovalue())) >= 0) {
			// 更新功力值为当前最大值
			ca.setGrowthvalue(new BigDecimal(nextGrade.getGrovalue()));
			clientAccomplishDao.updateByPrimaryKeySelective(ca);
			// 插入新的成就数据时
			ClientAccomplish c = new ClientAccomplish();
			c.setClientid(clientid);
			c.setGrade(mglist.get(i + 1).getGravalue());
			c.setGrowthvalue(newGrowth);
			c.setViewtime(ca.getViewtime());
			c.setCalorie(ca.getCalorie());
			c.setEnabled(true);
			c.setIsdeleted(false);
			c.setCreatedate(new Date());

			clientAccomplishDao.insert(c);

			i = i + 1;
			dealClientAccomplish(newGrowth, mglist, i, c, clientid);

		} else {
			ca.setGrowthvalue(newGrowth);
			clientAccomplishDao.updateByPrimaryKeySelective(ca);
			return;
		}
	}

	public MstOrderVo selectOrderByTradeNo(String tradeno) {
		return dao.selectOrderByTradeNo(tradeno);
	}

	/**
	 * 
	 * @Title: queryByList
	 * @Description: 数据集
	 * @param @param map
	 * @param @return pageBounds
	 * @return List<MstOrder> 返回类型
	 * @throws
	 */
	@Override
	public List<MstOrder> queryByList(Map<String, Object> map,
			PageBounds pageBounds) {
		return dao.queryByList(map, pageBounds);
	}

}
